//
//  ByCoreToolLocation.m
//  beibei_ios
//
//  Created by pro on 16/6/15.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByCoreToolLocation.h"
#import "ByCoreAddressSqlite3.h"
//#import "WGS84TOGCJ02.h"
#import "JZLocationConverter.h"
static ByCoreToolLocation *instance;        // 单例类
@interface ByCoreToolLocation()<BMKGeoCodeSearchDelegate>
{
    NSMutableDictionary *_tmp;
}
@property (nonatomic, strong) BMKGeoCodeSearch *search;
@end
@implementation ByCoreToolLocation
- (BMKGeoCodeSearch *)search {
    if (_search == nil) {
        _search = [[BMKGeoCodeSearch alloc] init];
        _search.delegate = self;
    }
    return _search;
}
#pragma mark - 实现单例
+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    //这个函数中的代码快任务只能执行一次。他是线程安全的。
    dispatch_once(&onceToken, ^{
        instance = [[ByCoreToolLocation alloc] init];
        instance.locationManager = [[CLLocationManager alloc] init];
        instance.geocoder = [[CLGeocoder alloc] init];
        
    });
    return instance;
}
// 实现一些限制方法，限制这个类始终只能创建一个对象，并且此对象不能销毁
+ (id)allocWithZone:(struct _NSZone *)zone {
    
    if (instance == nil) {
        instance = [super allocWithZone:zone];
    }
    return instance;
}

- (void)configLocationService {
    
    /** 未打开定位服务 */
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
    }
    /** 未授权则请求授权 */
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"未授权定位，请求授权");
        [self.locationManager requestWhenInUseAuthorization];
    } else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"已授权定位");
    }
}
#pragma mark - location delegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateLocations:(NSArray *)locations {
    
    CLLocation *location = [locations firstObject];             //取出第一个位置
//    //判断是不是属于国内范围
//    if (![WGS84TOGCJ02 isLocationOutOfChina:[location coordinate]]) {
//        //转换后的coord
//        CLLocationCoordinate2D coordinate = [WGS84TOGCJ02 transformFromWGSToGCJ:[location coordinate]];
//        [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
//        
//        // 如果不需要实时定位，使用完即使关闭定位服务
//        [_locationManager stopUpdatingLocation];
//    }else{
//        CLLocationCoordinate2D coordinate = location.coordinate;    //位置坐标
//        [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
//        
//        // 如果不需要实时定位，使用完即使关闭定位服务
//        [_locationManager stopUpdatingLocation];
//    }
    
    //转换后的coord
    CLLocationCoordinate2D coordinate = [JZLocationConverter wgs84ToBd09:[location coordinate]];
//    CLLocationCoordinate2D coordinate = location.coordinate;
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    // 如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
//    + (CLLocationCoordinate2D)wgs84ToBd09:(CLLocationCoordinate2D)location
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    
    if ([self.delegate respondsToSelector:@selector(locationDidFail:)]) {
        [self.delegate locationDidFail:error];
    }
    
}

#pragma mark - 全局方法
- (void)startUpdateLoaction {
    
    // 设置代理
    self.locationManager.delegate = self;
    // 设置定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 定位频率,每隔多少米定位一次
    CLLocationDistance distance = 10.0; // 十米定位一次
    self.locationManager.distanceFilter = distance;
    // 启动跟踪定位
    [self.locationManager startUpdatingLocation];
}


#pragma mark - 局部方法
- (void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    // 反地理编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    
    _tmp = [NSMutableDictionary new];
    [_tmp setObject:@(latitude) forKey:@"lat"];
    [_tmp setObject:@(longitude) forKey:@"lng"];

//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
//        dispatch_semaphore_signal(semaphore);
        CLPlacemark *placemark = [placemarks firstObject];
        _tmp = [[NSMutableDictionary alloc] initWithDictionary:placemark.addressDictionary];
        [_tmp setObject:@(latitude) forKey:@"lat"];
        [_tmp setObject:@(longitude) forKey:@"lng"];
        [_tmp setObject:[ByCoreAddressSqlite3 getProvinceID:_tmp[@"State"]] forKey:@"StateID"];
        [_tmp setObject:[ByCoreAddressSqlite3 getCityID:_tmp[@"City"] provinceID:_tmp[@"StateID"]] forKey:@"CityID"];
        
    }];
    
    
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    // 利用地理反编码获得地址  百度数据库
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
    option.reverseGeoPoint = location.coordinate;
    [self.search reverseGeoCode:option];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) { // 没错误
        

        NSLog(@"经纬度(%lf, %lf)", result.location.latitude, result.location.longitude);
        NSLog(@"address:%@", result.address);
        
        [_tmp setObject:result.addressDetail.province forKey:@"province"];
        [_tmp setObject:result.addressDetail.city forKey:@"city"];
        [_tmp setObject:result.addressDetail.district forKey:@"district"];
        [_tmp setObject:result.addressDetail.streetName forKey:@"streetName"];
        [_tmp setObject:result.addressDetail.streetNumber forKey:@"streetNumber"];
        [_tmp setObject:[ByCoreAddressSqlite3 getProvinceID:_tmp[@"province"]] forKey:@"provinceID"];
        [_tmp setObject:[ByCoreAddressSqlite3 getCityID:_tmp[@"city"] provinceID:_tmp[@"city"]] forKey:@"cityID"];

        if ([self.delegate respondsToSelector:@selector(locationDidComplete:)]) {
            [_tmp setObject:result.address forKey:@"addressBD"];
            [self.delegate locationDidComplete:[_tmp copy]];
        }
        
        
    } else {
        if ([self.delegate respondsToSelector:@selector(locationDidComplete:)]) {
            [_tmp setObject:@"" forKey:@"addressBD"];
            [self.delegate locationDidComplete:[_tmp copy]];
        }
        NSLog(@"地理反编码错误");
    }

}

@end
